package com.foogui.primary.sync;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

public class Pipe {
    public static void main(String[] args) throws IOException {

        PipedReader reader = new PipedReader();
        PipedWriter writer = new PipedWriter();
        reader.connect(writer);
        new Thread(new ThreadA(reader)).start();
        new Thread(new ThreadB(writer)).start();

    }
}
class ThreadA implements Runnable{
    private  PipedReader pipedReader;

    public ThreadA(PipedReader pipedReader) {
        this.pipedReader = pipedReader;
    }

    @Override
    public void run() {
        System.out.println("reader is starting");
        int len=0;
        try {
            while ((len=pipedReader.read())!=-1){
                System.out.println((char)len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                pipedReader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
class ThreadB implements Runnable{
    private  PipedWriter pipedWriter;

    public ThreadB(PipedWriter pipedWriter) {
        this.pipedWriter = pipedWriter;
    }

    @Override
    public void run() {
        System.out.println("writer is starting");
        try {
            pipedWriter.write("dsjal");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                pipedWriter.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}

